/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.jr.rest.handlers;

import cn.ac.iie.di.ban.jr.rest.server.TXRestStartup;
import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;

/**
 *
 * @author zwlin
 */
public class Handler implements HandlerI {

	public static Logger LOG = Logger.getLogger(Handler.class);

	static private final HashMap<String, JsonHandler> handlerMap = new HashMap<>();

	static public void regJsonHandler(JsonHandler handler) {
		handlerMap.put(handler.getDataType(), handler);
	}

	static private final String DATA_TYPE = "datatype";

	@Override
	public void init() throws Exception {
	}

	@Override
	public void execute(Request pRequest, HttpServletRequest request, HttpServletResponse response) throws Exception {
		LOG.debug("get value");
		ServletInputStream is = request.getInputStream();
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = is.read(buffer)) != -1) {
			out.write(buffer, 0, len);
		}
		String jsonStr = new String(out.toByteArray());
		LOG.debug("json str: " + jsonStr);
		JSONObject obj = null;
		try {
			obj = JSONObject.parseObject(jsonStr);
		} catch (Exception e) {
			LOG.error(ExceptionUtils.getFullStackTrace(e));
		}
		LOG.debug("json value: " + obj);
		if (obj.containsKey(DATA_TYPE)) {
			String datatype = obj.getString(DATA_TYPE);
			if (handlerMap.containsKey(datatype)) {
				JsonHandler jsonHandler = handlerMap.get(datatype);
				JsonHandler.Status status = jsonHandler.handle(obj);
				String rtn = JSON.toJSONString(status);
				response.getOutputStream().print(rtn);
				response.getOutputStream().flush();
				pRequest.setHandled(true);
			} else {
				//datatype不支持
			}
		} else {
			LOG.error("no dataType");
			//没有datatype
		}
	}

}
